package iss.java;
import iss.java.list.Node;
import java.util.concurrent.locks.ReadWriteLock;  
import java.util.concurrent.locks.ReentrantReadWriteLock; 
/**
 * Created by wenke on 2016/9/16.
 */
public class Main_A {
	public static ReadWriteLock lock = new ReentrantReadWriteLock(false);

    public static void main(String[] args) {
        // TODO: Implement a multithreaded test case against requirement A.
    	Node node = new Node(lock);
    	node.setData(1);
    	new Thread() {
    		public void run() {
    			for(int i = 0; i < 10; i++) {
    				if(i == 4) {
    					try {
							Thread.sleep(1);  // 用sleep来体现线程竞争
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
    				}
    				lock.writeLock().lock();
    				try {
    					node.setData(node.getData() - 2);
    				} finally {
    					lock.writeLock().unlock();
    				}
    				System.out.println("减2 " + node.getData());
    			}
    		}
    	}.start();
    	new Thread() {
    		public void run() {
    			for(int i = 0; i < 10; i++) {
    				lock.writeLock().lock();
    				try {
    					node.setData(node.getData() + 2);
    				} finally {
    					lock.writeLock().unlock();
    				}
    				System.out.println("加2 " + node.getData());
    			}
    		}
    	}.start();
    	new Thread() {
    		public void run() {
    			for(int i = 0; i < 10; i++) {
    				lock.writeLock().lock();
    				try {
    					node.setData(node.getData() + 1);
    				} finally {
    					lock.writeLock().unlock();
    				}
    				System.out.println("加1 " + node.getData());
    			}
    		}
    	}.start();
    }
}
